// import { mapState } from "vuex";
import cTitle from "components/title";
import yzSpecs from "components/ui_components/yz_specs";
import { Toast } from "vant";
import base64_encode from "../../utils/base64_encode";
import {bindDrainageScene} from "../../fun/modules/drainage_scene";
import yzAddressList from "components/ui_components/yz_addressList/index";


const SUBMIT_ACTION_CART = "-1"; //添加到购物车
export default {
  data() {
    return {
      multi_selection: true,
      activeTab: 0,
      TabList: [],
      integral: window.localStorage.integral || "积分",
      selectBol: true,
      cartDelete: false, //切换编辑状态
      eachCheckList: [], //每个店铺选中的商品购物车id
      eachCartsList: [], //每个店铺全部的商品
      allCartsList: [], //每个店铺全部的商品购物车id
      all_carts_id: [], //全部购物车id
      eachCheckShop: [], // 每个店铺是否全选的状态
      cart_ids: [], //选中的购物车id

      cartList: [], //购物车数据
      failureCartList: [], //失效商品数据
      total_goods_price: 0, //商品总价是优惠前的价格
      total_amount: 0, //合计总价
      point_mall_total: 0, //积分商品积分数量
      total_discount_amount: 0, //优惠
      discount_amount_items: [], //选中购物车优惠项

      // goodData: {}, //单个商品数据=>规格弹窗
      // goods_option_id: '', //单个商品规格id
      // popupSpecs: false, //规格弹窗显示
      // showCouponList: false, //优惠券弹窗显示
      showCouponDetail: false, //优惠明细弹窗显示
      isShowList: false, //购物车商品显示
      checkAll: false, //全选
      rentIndex: -1, // 判断购物车是否有租赁商品

      //结算标识
      submitFlag: "",

      //配送方式
      delivery_address: {},
      addressName: null,
      showAddress: false,
      showChoose: false,
      radioChoose: "",
      dispatch_types: [],
      chooseType: "", // 判断是否选中了租赁商品

      showMore: false,
      sharin_is_open: false, // 购物车分享
      vip_show: JSON.parse(window.localStorage.getItem("globalParameter")).vip_show ? JSON.parse(window.localStorage.getItem("globalParameter")).vip_show : false
    };
  },
  activated() {
    this.initView(); //初始化数据
    this.getTabData();//获取选项卡
  },

  methods: {
    //初始化view
    initView() {
      this.multi_selection = true;
      this.activeTab = 0;
      this.selectBol = true;
      this.cartDelete = false;
      this.eachCheckList = [];
      this.eachCartsList = [];
      this.allCartsList = [];
      this.all_carts_id = [];
      this.eachCheckShop = [];
      this.cart_ids = [];

      this.cartList = [];
      this.failureCartList = [];
      this.total_goods_price = 0;
      this.total_amount = 0;
      this.point_mall_total = 0;
      this.total_discount_amount = 0;

      // this.goodData = {};
      // this.popupSpecs = false;
      // this.showCouponList = false;
      this.showCouponDetail = false;
      this.isShowList = false;
      this.checkAll = false;
      this.rentIndex = -1;

      this.submitFlag = "";
      this.showChoose = false;
      this.radioChoose = "";
      this.dispatch_types = [];
      this.chooseType = "";
    },

    //清空失效购物车数据
    clearFailureCart() {
      let cart_id = [];
      this.failureCartList.forEach(element => {
        cart_id.push(element.id);
      });

      this.$dialog
        .confirm({ message: "确定清空失效商品吗？" })
        .then(() => {
          $http.post(this.activeTabInfo.url.del_failure,{cart_ids: cart_id}).then(
            response => {
              if (response.result === 1) {
                this.failureCartList = [];
                Toast("清空成功");
              }
            },
            response => {
              console.log(response);
            }
          );
        })
        .catch(() => {});
    },
    async getTabData(){
      let { result, msg, data } = await $http.get('cart.tab',{},".");
      if(result == 0) this.$toast(msg);
      this.TabList = data;
      let index = 0;
      if(this.$route.query.plugin_id) {
        index = data.findIndex(item => item.plugin_id == this.$route.query.plugin_id);
        this.activeTab = index;
      }
      this.multi_selection = data[index].multi_selection;
      this.activeTabInfo = data[index];
      this.getData();
    },
    onClickTab() {
      this.activeTabInfo = this.TabList[this.activeTab];
      this.multi_selection = this.activeTabInfo.multi_selection;
      this.getData();
    },
    //获取购物车数据
    getData(flag) {
      let json = {
        cart_ids: this.cart_ids.join(",")
      };
      if (flag === "delete") {
        // 获取购物车数量
        json.basic_info = 1;
      }
      $http.post(this.activeTabInfo.url.index, json, "loading").then(
        response => {
          if (response.result === 1) {
            this.sharin_is_open = response.data.sharin_is_open;
            this.total_discount_amount = response.data.total_discount_amount;
            this.discount_amount_items = response.data.discount_amount_items;
            this.total_amount = response.data.total_amount;
            this.point_mall_total = response.data.point_mall_total;
            this.total_goods_price = response.data.total_goods_price;
            this.cartList = response.data.list;
            this.failureCartList = response.data.invalid_cart || [];//获取失效购物车数据
            this.delivery_address = response.data.delivery_address;//默认地址
            if(this.delivery_address) this.addressInit();
            if (!flag) {
              this.allCheckListInit(this.cartList);
            } else if (flag === "delete") {
              this.allCheckListInit(this.cartList, flag);
            }
          } else {
            Toast(response.msg);
          }
        },
        response => {
          console.log(response);
        }
      );
    },

    //初始化全部数据
    allCheckListInit(data, flag) {
      this.cart_ids = [];
      this.eachCartsList = [];
      this.eachCheckList = [];
      this.eachCheckShop = [];
      if (flag == "delete" && data.length <= 0) {
        this.cartDelete = !this.cartDelete;
        this.checkAll = false;
      }

      if (data.length) {
        let list = [];
        let all_carts_id = [];
        for (let i = 0; i < data.length; i++) {
          this.eachCartsList[i] = data[i].carts;
          this.eachCheckList.push([]);
          this.eachCheckShop.push({ check: false, code: data[i].code, is_alone: data[i].is_alone });
          if (data[i].code === "lease-toy") {
            this.rentIndex = i;
          }
          list[i] = data[i].carts.map(item => {
            all_carts_id.push(item.cart_id);
            return item.cart_id;
          });
        }

        //取得购物车全部数据
        this.allCartsList = list;
        this.all_carts_id = all_carts_id;
        this.isShowList = true;
        // console.log(this.eachCartsList, this.eachCheckList,this.eachCheckShop,this.allCartsList, this.all_carts_id);
      }
    },

    selectBolfun(num) {
      // 判断点击是否点击全选 '1', 防止多次触发this.eachCheckList[c_index]变化allSelectHandle
      num === "1" ? (this.selectBol = true) : (this.selectBol = false);
    },

    //点击全选
    allSelect(event) {
      if (this.selectBol) {
        // console.log(this.selectBol, event, "全选");
        if (event) {
          if (this.allCartsList.length === 1) {
            // 判断只有租赁的情况
            this.chooseType = "rent";
            this.eachCheckList = JSON.parse(JSON.stringify(this.allCartsList));
            this.eachCheckShop[0].check = true;
          } else if (this.cartDelete) {
            // 删除操作的时候
            this.eachCheckList = [];
            let allCartsList = JSON.parse(JSON.stringify(this.allCartsList));
            for (let i = 0; i < allCartsList.length; i++) {
              this.eachCheckShop[i].check = true;
              this.eachCheckList.push(this.allCartsList[i]);
            }
          } else {
            // 租赁和平台混合
            this.chooseType = "buy";
            this.eachCheckList = [];
            let allCartsList = JSON.parse(JSON.stringify(this.allCartsList));
            for (let i = 0; i < allCartsList.length; i++) {
              if (this.eachCheckShop[i].is_alone) {
                this.eachCheckShop[i].check = false;
                this.eachCheckList.push([]);
              } else {
                this.eachCheckShop[i].check = true;
                this.eachCheckList.push(this.allCartsList[i]);
              }
            }
          }
        } else {
          this.chooseType = "";
          this.eachCheckList = [];
          for (let i = 0; i < this.allCartsList.length; i++) {
            this.eachCheckList.push([]);
            this.eachCheckShop[i].check = false;
          }
        }

        this.countCartView();
      }
    },

    //选择单个店铺商品购买监听 this.eachCheckList[c_index]变化会触发
    allSelectHandle(value, c_index) {
      // console.log(this.selectBol,value, c_index, "value");
      this.activeMerchantID = this.cartList[c_index].merchant_id;//当前点击的店铺id
      if (!this.selectBol) {
        this.eachCheckShop[c_index].check = value.length === this.eachCartsList[c_index].length;
        this.countCartView();
      }
      // console.log(this.eachCheckList,"this.eachCheckList");
    },

    // 点击整个店铺购买 通过触发this.eachCheckShop[c_index]请求
    shopChange(val, c_index) {
      if (this.cartList[c_index].disable) {
        return;
      }
      this.activeMerchantID = this.cartList[c_index].merchant_id;//当前点击的店铺id
      if (val) {
        // 先清空再赋值
        this.eachCheckList[c_index].splice(0, this.eachCheckList[c_index].length);
        this.eachCartsList[c_index].map(item => {
          this.eachCheckList[c_index].push(item.cart_id);
        });
      } else {
        this.eachCheckList[c_index].splice(0, this.eachCheckList[c_index].length);
      }
      // console.log(val, c_index, this.eachCheckList[c_index]);
    },

    //删除界面操作
    onCartDelete() {
      this.cartDelete = !this.cartDelete;
      this.chooseType = "";
      this.selectBolfun("1");
      //清空数据
      this.checkAll = false;
      this.eachCheckList = [];
      this.cart_ids = [];
      this.total_amount = 0;
      this.total_goods_price = 0;
      this.total_discount_amount = 0;
      for (let i = 0; i < this.eachCartsList.length; i++) {
        this.eachCheckList.push([]);
        this.cartList[i].disable = false;
        this.eachCheckShop[i].check = false;
      }
    },

    //删除商品
    deleteGoods() {
      if (this.cart_ids.length == 0) {
        Toast("请选择删除商品");
        return;
      }
      let json = {
        ids: this.cart_ids.join(",")
      };
      $http.get(this.activeTabInfo.url.destroy, json, "操作中").then(
        response => {
          if (response.result == 1) {
            this.getData("delete");
          } else {
            Toast(response.msg);
          }
        },
        response => {
          console.log(response);
        }
      );
    },

    // 检查配送方式是否冲突
    checkGoods() {
      let isBindDrainageScene = bindDrainageScene({
        scene: 1,
        title: '购物车'
      });
      if(!isBindDrainageScene) return;//爆客码绑定场景

      if (this.cart_ids.length == 0) {
        Toast(this.$i18n.t('base.selectSettlementItems'));
        return;
      }

      if(this.activeTabInfo.plugin_id != 0) {
        return this.submitGoods();
      }

      if (this.cart_ids.length > 50) {
        Toast("最多一次性只能下单50样商品");
        return;
      }

      let url = "memberCart.checkout";
      $http.get(url, { cart_ids: this.cart_ids.join(",") }, "操作中").then(
        response => {
          if (response.result == 1) {
            if (response.data.need_choose == 1) {
              this.dispatch_types = response.data.dispatch_types;
              this.showChoose = true;
            } else {
              this.submitGoods();
            }
          } else {
            this.$dialog.alert({
              title: "提示",
              message: response.msg
            });
          }
        },
        response => {
          console.log(response);
        }
      );
    },
    toBuy() {
      this.submitGoods();
    },
    checkPrice_difference_pool(basic_info){
      return new Promise((resolve, reject) => {
        $http.get("plugin.price-difference-pool.frontend.modules.pool.controllers.validate.index", {}).then(
          response => {
            if (response.result === 1) {
              resolve(true)
            } else {
              this.$dialog.confirm({ message: `${basic_info.price_difference_pool_name}为负数，请充值后再购买`, confirmButtonText: `去${basic_info.price_difference_pool_name}`})
                .then(() => {
                  this.$router.push(this.fun.getUrl("priceDifferencePool", {}, {}));
                }).catch(() => {
                  //取消
                });
              resolve(false)
            }
          },
          response => {
            this.$dialog.alert({ message: response.msg });
          }
        );
      })
    },
    //提交订单
    async submitGoods() {
      let _cart_ids = [];
      if (this.showChoose && !this.radioChoose) {
        Toast("请先选择配送方式");
        return;
      }

      if (this.showChoose) {
        // 配送方式有冲突
        for (let i = 0; i < this.dispatch_types[this.radioChoose].member_carts.length; i++) {
          _cart_ids.push(this.dispatch_types[this.radioChoose].member_carts[i].id);
        }
      } else {
        _cart_ids = this.cart_ids;
      }
      let basic_info = JSON.parse(localStorage.getItem("yz_basic_info"));
      if(basic_info.price_difference_pool){
        if(await this.checkPrice_difference_pool(basic_info) == false){
          return
        }
      }

      if(this.activeTabInfo.plugin_id == 181) {
        // 门店购物车结算
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              tag: "store",
              cart_ids: _cart_ids.join(","),
              store_id: this.activeMerchantID
            }
          )
        );
      }else if (this.chooseType === "rent") {
        // 租赁
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              tag: "rentCartBuy",
              cart_ids: _cart_ids.join(",")
            }
          )
        );
      } else if (this.chooseType === "buy") {
        this.$router.push(
          this.fun.getUrl(
            "goodsorder",
            {},
            {
              tag: SUBMIT_ACTION_CART,
              cart_ids: _cart_ids.join(",")
            }
          )
        );
      }
    },

    //跳转商品详情
    toGoodsInfo(goods) {
      if (goods.goods_option_id) {
        this.$router.push(this.fun.getUrl("goods", { id: goods.goods_id, coid: goods.goods_option_id }));
      } else {
        this.$router.push(this.fun.getUrl("goods", { id: goods.goods_id }));
      }
    },

    // 供应商
    toShop(item) {
      if(this.activeTabInfo.plugin_id == 181) {
        this.$router.push(this.fun.getUrl("o2oStore_v2", { store_id: item.merchant_id }));
      }else if (item.merchant_id) {
        this.$router.push(this.fun.getUrl("SupplierShop", { id: item.merchant_id }));
      }
    },

    // 凑单
    toSearch(item) {
      if(this.activeTabInfo.plugin_id == 181) {
        this.$router.push(this.fun.getUrl("StoreSearch", { store_id: item.merchant_id }));
      }else if (item.merchant_id) {
        this.$router.push(this.fun.getUrl("SupplierShop", { id: item.merchant_id }));
      } else {
        // search['plugin_id'] = 0 平台商品
        this.$router.push(this.fun.getUrl("search", {}, { plugin_id: 1 }));
      }
    },

    //改变数量
    changeCount(_num, cart_id, index, c_index) {
      if (_num < 0) {
        Toast("商品数量不能为负数");
        // 最少为1
        this.cartList[c_index].carts[index].total = 1;
        return;
      }

      let json = {
        id: cart_id,
        num: _num
      };
      $http.get(this.activeTabInfo.url.modify, json, "").then(
        response => {
          if (response.result === 0) {
            this.$dialog.alert({
              title: "提示",
              message: response.msg
            });
          }
          this.countCartView();
        },
        response => {
          console.log(response);
        }
      );
    },
    numberLeft(index, c_index) {
      // console.log(this.cartList[c_index].carts[index].total);
      if (this.cartList[c_index].carts[index].total <= 1) {
        Toast("商品数量不能为负数或零");
        return;
      }
      this.cartList[c_index].carts[index].total = Number(this.cartList[c_index].carts[index].total) - 1;
      this.changeCount(this.cartList[c_index].carts[index].total, this.cartList[c_index].carts[index].cart_id, index, c_index);
    },

    numberRight(index, c_index) {
      this.cartList[c_index].carts[index].total = Number(this.cartList[c_index].carts[index].total) + 1;
      // if (this.cartList[c_index].carts[index].total >= 51) {
      //   Toast("该商品每周最多可购买50件");
      //   this.cartList[c_index].carts[index].total = 1;
      //   return;
      // }
      this.changeCount(this.cartList[c_index].carts[index].total, this.cartList[c_index].carts[index].cart_id, index, c_index);
    },

    //计算总价格
    countCartView() {
      let cart_ids = [];
      for (let i = 0; i < this.eachCheckList.length; i++) {
        this.eachCheckList[i].map(item => {
          cart_ids.push(item);
        });
      }
      this.cart_ids = cart_ids;
      this.checkRent();
      this.checkChooseAll();
      if (!this.cartDelete) {
        this.getData("count");
      }
    },

    // 判断是否全选
    checkChooseAll() {
      if (this.cartDelete) {
        // 删除操作的时候
        if (this.all_carts_id.length === this.cart_ids.length) {
          //判断全选
          this.checkAll = true;
        } else {
          this.checkAll = false;
        }
      } else {
        let alone_num = 0;
        if (this.allCartsList.length > 1) {
          // 计算单独下单的商品数量 再判断是否全选
          for (let i = 0; i < this.allCartsList.length; i++) {
            if (this.eachCheckShop[i].is_alone) {
              alone_num = alone_num + this.allCartsList[i].length;
            }
          }
        }

        if (this.all_carts_id.length - alone_num === this.cart_ids.length) {
          //判断全选
          this.checkAll = true;
        } else {
          this.checkAll = false;
        }
      }
    },

    // 判断是否选中了租赁商品
    checkRent() {
      if (this.cart_ids.length > 0) {
        if(this.activeTabInfo.plugin_id != 0) {
          this.chooseType = "";
        } else if (this.rentIndex > -1 && this.eachCheckList[this.rentIndex].length > 0) {
          this.chooseType = "rent";
        } else {
          this.chooseType = "buy";
        }
      } else {
        // 全部清空
        this.chooseType = "";
      }
    },
    toShowMore() {
      this.showMore = !this.showMore;
    },
    shareCartGood() {
      this.$router.push(this.fun.getUrl("CartShare"));
    },
    toAuthorizedLogin(){
      this.$router.push(this.fun.getUrl("AuthorizedLogin",{},{yz_redirect: base64_encode(document.location.href)}));
    },
    addressInit(data) {
      // 处理地址信息
      let { province = '', city = '', district = '', street = '', address = '' } = data||this.delivery_address.address;
      let addressq = `${province}${city}${district}${street}${address}`;
      this.addressName = addressq || '请选择收货地址';
    },
    confirmSelectAddress(data) {
      this.addressInit(data);
      this.setDefaultAdress(data);
    },
    async setDefaultAdress(item){
      let json = {
        username: item.username,
        mobile: item.mobile,
        province: item.province,
        city: item.city,
        district: item.district,
        address: item.address,
        isdefault: 1,
        address_id: item.id,
        street: item.street||''
      };
      let { result, msg } = await $http.get('member.member-address.update',json,".");
      if(result == 0) this.$toast(msg);
      this.getData();
    },
    // openSpecs(item) {
    //   if(item.goods_option_title) {
    //     this.goods_option_id = item.goods_option_id;
    //     this.getGood(item.goods_id);
    //   }
    // },
    // close_yz_specs_popup(_optionsId, goodsCount, clicktype) {
    //   this.optionsId = _optionsId;
    //   this.goodsCount = goodsCount;
    //   this.popupSpecs = false;
    //   if (clicktype == 1) {
    //     //点击确认按钮
    //   }
    // },
    // //获取商品数据
    // getGood(id) {
    //   $http.post("goods.goods.get-goods-page", {
    //     id: id,
    //   }, " ").then(
    //     (res)=> {
    //       if (res.result === 1) {
    //         this.goodData = res.data.get_goods;
    //         this.popupSpecs = true;
    //       }
    //     }, (res)=> {
    //       console.log(res);
    //     }
    //   );
    // },
  },
  components: { cTitle, yzSpecs,yzAddressList }
};
